package com.yonyou.cyxdms.sysAuth.service.utill;

import com.google.common.collect.Maps;
import org.springframework.cglib.beans.BeanMap;

import java.util.List;
import java.util.Map;

/**
 * DTO 与 PO 拷贝工具类
 *
 * @author chengliang
 * @since 2019-09-17
 */
public class BeanUtils {
    /**
     *
     * ListDTO 与 ListPO 拷贝
     *
     * @param sourcepo
     * @param targetDTO
     * @param targetdtoclass
     * @param <T1>
     * @param <T2>
     *
     */
    public static <T1, T2> void copyProperties(List<T1> sourcepo, List<T2> targetDTO, Class<T2> targetdtoclass) {
        for (T1 t1 : sourcepo) {
            try {
                T2 t2 = targetdtoclass.newInstance();
                org.springframework.beans.BeanUtils.copyProperties(t1, t2);
                targetDTO.add(t2);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     *
     * PO 拷贝到 DTO
     *
     * @param <T1>
     * @param <T2>
     *
     */
    public static <T1, T2> void copyProperties(T1 sourceDTO, T2 targetpo ) {
        try {
            org.springframework.beans.BeanUtils.copyProperties(targetpo, sourceDTO);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将javabean对象转换为map
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = Maps.newHashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                Object value = beanMap.get(key);
                map.put(key + "", value);
            }
        }
        return map;
    }

}
